package com.hyperion.blog.admin.service;

import com.hyperion.blog.admin.pojo.Admin;
import com.hyperion.blog.admin.pojo.Permission;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.hyperion.blog.admin.constant.ConstantPackage.ANONYMOUS_USER;

/**
 * @author Hyperion
 * @date 2021/10/24
 */
@Service
@Slf4j
public class AuthService {

    @Resource
    private AdminService adminService;

    public boolean auth(HttpServletRequest request, Authentication authentication) {
        String requestURI = request.getRequestURI();
        Assert.notNull(requestURI, "请求异常");
        Object principal = authentication.getPrincipal();
        UserDetails userDetails = (UserDetails) principal;
        if (principal == null || ANONYMOUS_USER.equals(userDetails.getUsername())) {
            //未登录
            return false;
        }
        String username = userDetails.getUsername();
        Admin admin = adminService.findAdminByUserName(username);
        if (admin == null) {
            return false;
        }
        Long adminId = admin.getId();
        if (adminId == 1) {
            return true;
        }
        List<Permission> permissions = adminService.getPermissionByAdminId(adminId);
        requestURI = StringUtils.split(requestURI, '?')[0];
        for (Permission permission : permissions) {
            if (requestURI.equals(permission.getPath())) {
                log.info("权限通过");
                return true;
            }
        }
        return false;
    }
}
